package com.copc.common.util;


import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import lombok.extern.log4j.Log4j2;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;


/**
 * 工具类
 *  @author yuanbin
 */
@Component
@Log4j2
public class RiskUtil {


    public static String riskRequest(
            RestTemplate restTemplate,String url,Object data) throws UnsupportedEncodingException {

        HttpHeaders headers = new HttpHeaders();
        headers.add("Accept", MediaType.APPLICATION_JSON_VALUE);
        headers.add("Content-Type", MediaType.APPLICATION_JSON_VALUE);
        log.info("inputData=>" + data);
        log.info("applyUrl=>" + url);
        HttpEntity<String> entity = new HttpEntity<>(JSON.toJSONString(data),headers);
        String response = restTemplate.postForObject(url,
                entity, String.class);

        log.info("response data=>" + response);
        return response;
    }


    public static String postData(String url, String param) {
        JSONObject result = new JSONObject();

        HttpPost httpPost = new HttpPost(url);
        CloseableHttpClient client = HttpClients.createDefault();
//请求参数转JOSN字符串
        StringEntity entity = new StringEntity(param, "UTF-8");
        entity.setContentEncoding("UTF-8");
        entity.setContentType("application/json");
        httpPost.setEntity(entity);

        HttpResponse response = null;
        try {
            response = client.execute(httpPost);
            if (response.getStatusLine().getStatusCode() == 200) {
                result = JSON.parseObject(EntityUtils.toString(response.getEntity(), "UTF-8"));
            }
        } catch (IOException e) {
            e.printStackTrace();
            result.put("error", "连接错误！");
        }

        return response.toString();
    }



}
